package com.shop.cloud.pay.admin.config;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.shop.cloud.pay.admin.service.PayConfigService;
import com.shop.cloud.pay.common.constant.PayConstants;
import com.shop.cloud.pay.common.entity.PayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * 微信支付Configuration
 * @author
 *
 */
@Slf4j
@Configuration
public class WxPayConfiguration {

	private static PayConfigService payConfigService;

	@Autowired
	public WxPayConfiguration(PayConfigService payConfigService) {
		this.payConfigService = payConfigService;
	}

	/**
	 *  获取WxPayService
	 * @param wxPayConfig wxPayConfig.appId、wxPayConfig.subAppId
	 * @return
	 */
	public static WxPayService getPayService(WxPayConfig wxPayConfig) {
		WxPayService wxPayService = null;
		PayConfig payConfig = payConfigService.findByType(PayConstants.PAY_TYPE_1);
		if(payConfig!=null) {
			wxPayConfig.setAppId(payConfig.getAppId());
			wxPayConfig.setMchId(payConfig.getMchId());
			wxPayConfig.setMchKey(payConfig.getMchKey());
			wxPayConfig.setKeyPath(payConfig.getKeyPath());
			wxPayConfig.setPrivateKeyPath(payConfig.getPrivateKeyPath());
			wxPayConfig.setPrivateCertPath(payConfig.getPrivateCertPath());
			wxPayConfig.setCertSerialNo(payConfig.getCertSerialNo());
			wxPayConfig.setApiV3Key(payConfig.getApiV3Key());
			// 可以指定是否使用沙箱环境
			wxPayConfig.setUseSandboxEnv(false);
			wxPayService = new WxPayServiceImpl();
			wxPayService.setConfig(wxPayConfig);
		}else{
			throw new RuntimeException("请配置收款账号");
		}
		return wxPayService;
	}
}
